<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="AddRoles"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column
                label="序号"
                type="index"
                :index="table_index"
                width="120"
              />
              <el-table-column label="角色名称" prop="name" width="240" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                // eslint-disable-next-line vue/no-unused-vars
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="success"
                    @click="hAssign(scope.row.id)"
                  >分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="hEdit(scope.row)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delRoles(scope.row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- total:总条数
                 current-page：当前页数
                  page-sizes 每页显示个数选择器的选项设置
                  page-size 每个页面的条数
                  size-change pageSize 每页条数 改变时会触发
                  current-change 当前页 currentPage 改变时会触发
                  layout 组件布局，子组件名用逗号分隔
               -->
              <!-- 分页组件 -->
              <el-pagination
                :total="total"
                :current-page="page"
                :page-sizes="[1, 2, 50, 100]"
                :page-size="pagesize"
                layout="prev,pager,next,sizes"
                @size-change="hSizeChange"
                @current-change="hCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 新增弹框 -->
    <el-dialog
      :title="isEdit ? '编辑弹层' : '添加弹窗'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="hClose"
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small">取消</el-button>
          <el-button
            size="small"
            type="primary"
            @click="hSubmit"
          >确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog
      v-if="showDialogPermission"
      :title="'分配权限'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogPermission"
    >
      <AssignPermission :role-id="roleId" @success="hSuccess" />
    </el-dialog>
  </div>
</template>
<script>
import { getRoles, getDelRoles, addRoles, updateRoles } from '@/api/settings'
import AssignPermission from './assignPermission.vue'
export default {
  components: {
    AssignPermission
  },
  data() {
    return {
      roleId: '',
      showDialogPermission: false,
      isEdit: false,
      total: null,
      list: [],
      page: 1,
      pagesize: 2,
      showDialog: false,
      roleForm: {
        name: '程序员',
        description: '码农罢了'
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadRoles()
    // 自动删除
    // this.setTimeDel()
    // 自动添加
    // this.add()
    // 自动刷新
    // this.reflush()
  },
  methods: {
    hSuccess() {
      this.showDialogPermission = false
      this.$message.success('添加权限成功')
    },
    hAssign(id) {
      this.showDialogPermission = true
      this.roleId = id
    },
    hClose() {
      this.roleForm = {}
      this.$refs.roleForm.resetFields()
    },
    hEdit(data) {
      this.isEdit = true
      this.showDialog = true
      // 数据回填
      this.roleForm = { ...data }
    },
    async doAdd() {
      try {
        await addRoles(this.roleForm)
        this.total++
        this.page = Math.ceil(this.total / this.pagesize)
        this.$message.success('添加成功')
        this.showDialog = false
        this.loadRoles()
      } catch (error) {
        console.log(error)
        this.$message.error('添加失败')
      }
    },
    async doEdit() {
      try {
        await updateRoles(this.roleForm)
        this.$message.success('修改成功')
        this.showDialog = false
        this.loadRoles()
      } catch (error) {
        console.log(error)
        this.$message.error('添加失败')
      }
    },
    AddRoles() {
      this.showDialog = true
      this.isEdit = false
    },
    hSubmit() {
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    reflush() {
      setTimeout(() => {
        window.location.reload()
      }, 4000)
    },
    async add() {
      for (let i = 0; i < 100; i++) {
        await addRoles({ name: `勇士总冠军 ${i}`, description: `库里yyds` })
      }
    },
    async setTimeDel() {
      await getRoles({ page: 1, pagesize: 100 })
      const id = this.list.map((item) => item.id)
      id.forEach((item) => {
        setTimeout(function() {
          getDelRoles(item)
        }, 100)
      })
    },
    table_index(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    async delRoles(id) {
      await getDelRoles(id)
      if (this.list.length === 1 && this.page > 1) {
        this.page--
      }
      this.$message.success('删除成功')
      this.loadRoles()
    },
    // 每页条数
    hSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.loadRoles()
    },
    // 当前页
    hCurrentChange(val) {
      this.page = val
      this.loadRoles()
    },
    async loadRoles() {
      try {
        const res = await getRoles({ page: this.page, pagesize: this.pagesize })
        console.log(res)
        this.total = res.data.total
        this.list = res.data.rows
      } catch (err) {
        this.$message.error(err)
      }
    }
  }
}
</script>
